/**
*
* @title: jQuery "Only Left Mouse Click" event plugin
* @author: Golikov Yury
* @copyright: Golikov Yury, 2011
* @license: GNU General Public License v3.0
*
*/

if (jQuery) jQuery.event.special.leftclick = {	// define a new special event 'leftclick'
	setup: function(data, namespaces) {
		// called when bind
		var $obj = jQuery(this);
		$obj.bind('mousedown mouseup', jQuery.event.special.leftclick.handler);
	},
	teardown: function(namespaces) {
		// called when unbind
		var $obj = jQuery(this);
		$obj.unbind('mousedown mouseup', jQuery.event.special.leftclick.handler);
	},
	handler: function(e) {
		var $obj = jQuery(this);
		// cycle through event types
		if (e.type=='mousedown') { // mouse button pressed
			switch (e.which) { // which one?
				case 1: { // left
					// check for special keys
					if (!e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
						$obj.data('leftMouse',1); // save left button state
						$obj.data('clientX',e.clientX); // save X coord for later check
						$obj.data('clientY',e.clientY); // save Y coord for later check
					} else {
						$obj.data('leftMouse',0); // discard left button state
					}
					break;
				}
				case 2: { // middle
					$obj.data('middleMouse',1); // save middle button state
					$obj.data('leftMouse',0); // discard left button state
					break;
				}
				case 3: { // right
					$obj.data('rightMouse',1); // save right button state
					$obj.data('leftMouse',0); // discard left button state
					break;
				}
			}
		} else if (e.type = 'mouseup') { // mouse button released
			switch (e.which) { // which one?
				case 1: { // left
					if ($obj.data('leftMouse') && !$obj.data('middleMouse') && !$obj.data('rightMouse')
					// check for special keys
					&& !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey
					// check whether user dragged the mouse
					&& ($obj.data('clientX')-e.clientX)==0 && ($obj.data('clientY')-e.clientY)==0) {
						e.type = "leftclick"; // set event type
						jQuery.event.handle.apply(this, arguments); // let jquery call the handler
						$obj.data('leftMouse',0); // discard left button state
					}
					break;
				}
				case 2: { // middle
					$obj.data('middleMouse',0); // discard middle button state
					break;
				}
				case 3: { // right
					$obj.data('rightMouse',0); // discard right button state
					break;
				}
			}
		}
	}
};